import type {Router} from "vue-router";
import {useUserStore} from "../stores/user.ts";
import checkRole from "./checkRole.ts";
import USER_ROLE_ENUM from "./userRoleEnum.ts";
import {ElMessage} from "element-plus";

export const initAuth = (router: Router) => {
    const store = useUserStore();

    router.beforeEach(async (to, from, next) => {
        //console.log(store.userRole)
        if (!store.id || !store.userRole || store.userRole === ''){
            try {
                await store.fetchUserInfo();
            } catch (e) {
                store.resetUserState();
            }
        }

        // 判断是否需要登录
        if (!to.meta.public && store.userRole === USER_ROLE_ENUM.NOT_LOGIN) {
            if (to.path === "/home" || to.path === "/club/list" || to.path === "/activity/list") {
                next();
            } else if (to.path !== "/login") {
                ElMessage.error("此页面需要登录后才可查看，即将跳转到登录页");
                next("/login");
            } else {
                next();
            }
        }

        const needRoles = (to.meta?.needRoles as string[] | undefined);
        const checkedRoles = [] as boolean[];
        if (needRoles && needRoles.length > 0) {
            for (const role of needRoles) {
                checkedRoles.push(await checkRole(store.userRole, role));
            }
            for (const check of checkedRoles) {
                if (check) {
                    next();
                }
            }
            next({ path: '/no-auth' });
            return;
        }
        next()
    })
}